﻿using RabbitMQ.Client;
using System;
using RabbitMQ.Client.Events;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuanYijia.Application.ProductionManagement
{
    public class Recevie
    {
        public static async Task ReceiveMessage()
        {
            string queueName = "simple_order";
            using (IConnection? connection =  RabbitMQHelper.GetConnection())
            {
                var channel = await connection.CreateChannelAsync();

                // 创建队列
                await channel.QueueDeclareAsync(queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);

                var consumer = new AsyncEventingBasicConsumer(channel);
                int i = 0;

                // 事件处理方法，需要返回 Task
                consumer.ReceivedAsync += async (model, ea) =>
                {
                    // 消费者业务处理
                    var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                    Console.WriteLine($"{i}, 队列 {queueName} 消费消息: {message}");
                    i++;
                    // 如果需要异步执行其他任务，可以返回一个 Task。
                    await Task.CompletedTask;
                };

                // 启动消费者
                await channel.BasicConsumeAsync(queueName, true, consumer);
            }
        }
    }
    
}
